package com.lzx.mall_tiny01.service.impl;

import com.lzx.mall_tiny01.common.api.ResponseVo;
import com.lzx.mall_tiny01.component.Redis.RedisService;
import com.lzx.mall_tiny01.service.UmsMemberService;
import org.apache.logging.log4j.util.Strings;
import org.mybatis.generator.internal.util.StringUtility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;

/**
 * @Author: lzx
 * @Date: 2021/4/26 14:52
 */
@Service
public class UmsMemberServiceImpl implements UmsMemberService {
    @Autowired
    private RedisService redisService;
    @Value("${redis.key.prefix.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;
    @Value("${redis.key.expire.authCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS;
    /**
     * 生成验证码
     *
     * @param telephone
     * @return
     */
    @Override
    public ResponseVo generateAuthCode(String telephone) {
        StringBuilder builder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            builder.append(random.nextInt(10));
        }
        redisService.set(REDIS_KEY_PREFIX_AUTH_CODE+telephone,builder.toString());
        redisService.expire(REDIS_KEY_PREFIX_AUTH_CODE+telephone,AUTH_CODE_EXPIRE_SECONDS);
        return ResponseVo.success(builder.toString(),"获取验证码成功");
    }

    /**
     * 判断验证码是否正确
     *
     * @param telephone
     * @param authCode
     * @return
     */
    @Override
    public ResponseVo verifyAuthCode(String telephone, String authCode) {
        if (Strings.isEmpty(authCode)) {
            return ResponseVo.failure("请输入验证码");
        }
        String realAuthCode = redisService.get(REDIS_KEY_PREFIX_AUTH_CODE+telephone);
        if (authCode.equals(realAuthCode)) {
            return ResponseVo.success(null,"验证码校验成功");
        }else {
            return ResponseVo.failure("验证码不正确");
        }
    }
}
